<?php 

class AppCaptcha extends CCaptchaAction
{
	public $mobile;
	public function __construct($controller,$id)
	{
		$this->mobile = $_REQUEST['username']?$_REQUEST['username']:null;
		if($this->mobile && User::mobileRegistered($this->mobile))
			parent::__construct($controller,$id);
		else
		{
			echo json_encode(array(
				'success' => 0,
				'msg'    => 'illegal request',
			));
			Yii::app()->end();
		}
	}

	public function run()
	{
		$this->renderImage($this->getVerifyCode(true));
		Yii::app()->end();
	}

	public function getVerifyCode($regenerate=false)
	{
		if($this->fixedVerifyCode !== null)
			return $this->fixedVerifyCode;
		$cache   = Yii::app()->cache_php;
		if(!$cache->get('captcha.'.$this->mobile) || $regenerate)
		{
			$cache->set('captcha.'.$this->mobile,$this->generateVerifyCode());
			$cache->set('captcha.'.$this->mobile.'.count',1);
		}
		return $cache->get('captcha.'.$this->mobile);
	}

	public function validate($input,$caseSensitive)
	{
		$code  = $this->getVerifyCode();
		$valid = $caseSensitive ? ($input === $code) : strcasecmp($input,$code)===0;
		$cache = Yii::app()->cache_php;
		$count = $cache->get('captcha.'.$this->mobile.'.count');
		$cache->set('captcha.'.$this->mobile.'.count',$count+1);
		if($count+1 > $this->testLimit && $this->testLimit > 0)
			$this->getVerifyCode(true);
		return $valid;
	}
}